﻿using IOP.Net;
using IOP.Pulsar.Abstractions;
using System;
using System.Collections.Concurrent;

namespace IOP.Pulsar.Server
{
    /// <summary>
    /// 嵌套字池
    /// </summary>
    public class SocketPool : ISocketPool
    {
        /// <summary>
        /// Socket队列
        /// </summary>
        private readonly ConcurrentQueue<SocketMonitor> sockets = new ConcurrentQueue<SocketMonitor>();

        /// <summary>
        /// 构造函数
        /// </summary>
        public SocketPool()
        {
        }

        /// <summary>
        /// 出队列
        /// </summary>
        /// <returns></returns>
        public SocketMonitor DequeneSocket()
        {
            while (!sockets.IsEmpty)
            {
                if(sockets.TryDequeue(out SocketMonitor socket))
                    if (!socket.ConnectedSocket.Connected) return socket;
            }
            var newSocket = new SocketMonitor(null);
            var newGuid = Guid.NewGuid();
            newSocket.Identifier = newGuid.ToString("N");
            newSocket.Guid = newGuid;
            return newSocket;
        }
        /// <summary>
        /// 入队列
        /// </summary>
        public void EnqueueSocket(SocketMonitor socket)
        {
            sockets.Enqueue(socket);
        }
    }
}
